﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using com.Bliss;
using System.Configuration;
using System.Web.UI.WebControls;
using com.Bliss.Services;
using com.Bliss.ServiceFacade.Post.Request;
using com.Bliss.ServiceFacade.User.Request;

namespace mojoPortal.Web.RS.Bliss.Controls
{
    public partial class GetPrivateMessages : com.Bliss.UI.Common.UserControlBase
    {
        #region Public UserControlProperty
        public string OP_SSOToken
        {
            get
            {
                return hdnOP_SSoToken.Value;
            }
            set
            {
                hdnOP_SSoToken.Value = value;
            }
        }
        public int OP_LoggedInUserId
        {
            get
            {
                int returnValue = 0;
                int.TryParse(hdnOP_LoggedInUserId.Value, out returnValue);
                return returnValue;
            }
            set
            {
                hdnOP_LoggedInUserId.Value = value.ToString();
            }
        }
        private int OP_CompanyID
        {
            get
            {
                int returnValue = 0;
                int.TryParse(hdnOP_CompanyID.Value, out returnValue);
                return returnValue;
            }
            set
            {
                hdnOP_CompanyID.Value = value.ToString();
            }
        }
        private string OP_UserName
        {
            get
            {
                return hdnOP_UserName.Value;
            }
            set
            {
                hdnOP_UserName.Value = value;
            }
        }
        private string OP_ImageName
        {
            get
            {
                return hdnOP_ImageName.Value;
            }
            set
            {
                hdnOP_ImageName.Value = value;
            }
        }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ClearMessage();
                if (OP_SSOToken == string.Empty)
                {
                    ExceptionMessage = "User Token propertiey not set.";
                    return;
                }
                else
                {
                    IUserService service = new UserService();
                    var user = service.ValidateUserSsoToken(new ValidateUserSsoTokenRequest() { SsoToken = OP_SSOToken });
                    if (user.Data == null)
                    {
                        ExceptionMessage = "Invalid User Token provided";
                        return;
                    }
                    else
                    {
                        OP_CompanyID = user.Data.CompanyID;
                        OP_LoggedInUserId = user.Data.ID;
                        OP_UserName = user.Data.Email;
                        OP_ImageName = user.Data.ImageName;
                    }
                }
                BindGrid();
            }
        }
        private void BindGrid()
        {
            IPostService service = new PostService();
            var res = service.GetPrivatePosts(new GetPrivatePostRequest { UserID = OP_LoggedInUserId });
            List<IPost> lstPost = res.DataCollection.ToList();
            lstPost.ForEach(p => p.Comments = p.Comments.OrderBy(q => q.SendDate).ToList());
            lstPost = lstPost.OrderByDescending(p => p.SendDate).ToList();
            GridViewWallPosts.PageIndex = GridViewWallPosts.PageIndex;
            GridViewWallPosts.DataSource = lstPost;
            GridViewWallPosts.DataBind();
        }
        private void BindGridToChild(GridView childGridView, int ParentID)
        {
            IPostService service = new PostService();
            var res = service.GetChildPosts(new GetChildPostRequest { ParentId = ParentID });
            List<IPost> lstPost = res.DataCollection.ToList();
            lstPost = lstPost.OrderBy(p => p.SendDate).ToList();
            childGridView.PageIndex = childGridView.PageIndex;
            childGridView.DataSource = lstPost;
            childGridView.DataBind();
        }
        protected void rptUserDetails_ItemCommand(object source, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("DeletePost"))
            {
                int postID = Convert.ToInt32(e.CommandArgument);
                IPostService service = new PostService();
                service.DeletePost(new DeletePostRequest { PostID = postID });
                GridView grdChild = ((ImageButton)e.CommandSource).Parent.Parent.Parent.Parent.Parent.Parent as GridView;
                GridViewRow gvRowParent = ((ImageButton)e.CommandSource).Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent as GridViewRow;
                HiddenField hdnID = gvRowParent.FindControl("hdnID") as HiddenField;
                BindGridToChild(grdChild, int.Parse(hdnID.Value));
            }
        }
        public void rptUserDetails_ItemDataBound(object sender, GridViewRowEventArgs e)
        {
            GridViewRow gvr = e.Row;
            //ImageButton imgDeletePost = gvr.FindControl("imgDeletePost") as ImageButton;
            //if (imgDeletePost != null)
            //{
            //    imgDeletePost.Attributes.Add("onclick", "javascript:return confirm('Are you sure that you want to delete this Reply ?')");
            //    IPost post = (IPost)gvr.DataItem;

            //    if (post.PostedBy.ID == UserID.Value || post.Parent.PostedBy.ID == UserID.Value)
            //    {
            //        imgDeletePost.Visible = true;
            //    }
            //    else
            //    {
            //        imgDeletePost.Visible = false;
            //    }
            //}

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                System.Web.UI.HtmlControls.HtmlTableRow itemRow = gvr.FindControl("itemRow") as System.Web.UI.HtmlControls.HtmlTableRow;
                //itemRow.Attributes["onmouseover"] = "this.style.backgroundColor='Pink'";
                //itemRow.Attributes["onmouseover"] = "this.style.backgroundColor='#F5F5F5'";
                itemRow.Attributes["onmouseover"] = "this.style.backgroundColor='#F0F3F4'";
                itemRow.Attributes["onmouseout"] = "this.style.backgroundColor='Transparent'";
            }
        }
        protected void rptUserDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView grdChild = (GridView)sender;
            GridViewRow gvRowParent = ((GridView)sender).Parent.Parent as GridViewRow;
            HiddenField hdnID = gvRowParent.FindControl("hdnID") as HiddenField;
            grdChild.PageIndex = e.NewPageIndex;
            BindGridToChild(grdChild, int.Parse(hdnID.Value));
        }
        protected void GridViewWallPosts_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridViewRow gvr = null;
            HiddenField hdnID = null;
            int ParentID = 0;
            if (e.CommandName == "Reply")
            {
                gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                hdnID = gvr.FindControl("hdnID") as HiddenField;
                if (hdnID != null)
                {
                    ParentID = Convert.ToInt32(hdnID.Value);
                    TextBox txtReply = gvr.FindControl("txtReply") as TextBox;
                    if (txtReply != null)
                    {
                        string message = txtReply.Text;
                        IPostService service = new PostService();
                        service.SendPrivateMessage(new SendPrivateMessageRequest { FromUserID = OP_LoggedInUserId, ParentPostID = ParentID, ToUserID = null, Message = GetLineBreaks(message) });
                        GridView rptUserDetails = gvr.FindControl("rptUserDetails") as GridView;
                        if (rptUserDetails != null)
                        {
                            rptUserDetails.PageIndex = rptUserDetails.PageCount;
                            BindGridToChild(rptUserDetails, ParentID);
                        }
                        txtReply.Text = "";
                    }
                }
            }
            else if (e.CommandName == "DeleteMainPost")
            {
                gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
                hdnID = gvr.FindControl("hdnID") as HiddenField;
                if (hdnID != null)
                {
                    ParentID = Convert.ToInt32(hdnID.Value);
                    IPostService service = new PostService();
                    service.DeletePost(new DeletePostRequest { PostID = ParentID });
                    BindGrid();
                }
            }

        }
        protected void GridViewWallPosts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridViewRow gvr = e.Row;
            IPost post = gvr.DataItem as IPost;
            //ImageButton imgDeleteMainPost = gvr.FindControl("imgDeleteMainPost") as ImageButton;
            //if (imgDeleteMainPost != null)
            //{
            //    imgDeleteMainPost.Attributes.Add("onclick", "javascript:return confirm('Are you sure that you want to delete this Post ?')");
            //    IPost post = (IPost)gvr.DataItem;
            //    if (post.PostedBy.ID == UserID.Value)
            //    {
            //        imgDeleteMainPost.Visible = true;
            //    }
            //    else
            //    {
            //        imgDeleteMainPost.Visible = false;
            //    }
            //}
            HtmlImage imgReceive = gvr.FindControl("imgReceive") as HtmlImage;
            HtmlImage imgSend = gvr.FindControl("imgSend") as HtmlImage;
            //LinkButton lnkUser = gvr.FindControl("lnkUser") as LinkButton;
            HtmlGenericControl spnLnkUser = gvr.FindControl("spnLnkUser") as HtmlGenericControl;
            //if (imgReceive != null && lnkUser != null && imgSend != null && spnLnkUser!= null)
            if (imgReceive != null  && imgSend != null && spnLnkUser != null)
            {
                if (post.ToID == OP_LoggedInUserId)
                {
                    imgSend.Visible = true;
                    imgReceive.Visible = false;
                    //lnkUser.Visible = false;
                }
                else if (post.FromId == OP_LoggedInUserId)
                {
                    imgReceive.Visible = true;
                    imgSend.Visible = false;
                    spnLnkUser.InnerHtml = "<b>" + post.PostedTo.Name + "</b>";
                    //lnkUser.Visible = true;
                    //lnkUser.Text = post.PostedTo.Name;
                    //lnkUser.PostBackUrl =  ResolveUrl("~/UserDetails.aspx?Id=" + post.PostedTo.ID.ToString());
                }
            }

            GridView rptUserDetails = gvr.FindControl("rptUserDetails") as GridView;
            if (rptUserDetails != null)
            {
                rptUserDetails.DataSource = post.Comments;
                rptUserDetails.DataBind();
            }

            RequiredFieldValidator reqReply = gvr.FindControl("reqReply") as RequiredFieldValidator;
            Button btnReply = gvr.FindControl("btnReply") as Button;
            if (btnReply != null)
            {
                TextBox txtReply = gvr.FindControl("txtReply") as TextBox;
                string validationGroup = Guid.NewGuid().ToString();
                btnReply.ValidationGroup = validationGroup;
                reqReply.ValidationGroup = validationGroup;
            }
        }
        protected void GridViewWallPosts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridViewWallPosts.PageIndex = e.NewPageIndex;
            BindGrid();
        }

    }
}